package com.example.todolist.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.todolist.dto.sys.EditUserInfoDTO;
import com.example.todolist.model.SysUser;
import com.example.todolist.mapper.SysUserMapper;
import com.example.todolist.model.TeamFarDO;
import com.example.todolist.model.TeamPerDO;
import com.example.todolist.response.BaseResponse;
import com.example.todolist.response.SystemResponse;
import com.example.todolist.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.todolist.util.HttpServletRequestUtil;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2022-02-24
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Override
    public SysUser selectByOpenId(String openId) {
        return getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getWxOpenId, openId));
    }

    @Override
    public BaseResponse getUserInfo() {
        String uid = (String) HttpServletRequestUtil.getHttpServletRequest().getAttribute("uid");
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<SysUser>().eq(SysUser::getUid, uid);
        return SystemResponse.success(this.baseMapper.selectOne(lambdaQueryWrapper));
    }

    @Override
    public BaseResponse editUserInfo(EditUserInfoDTO editUserInfoDTO) {
        String uid = (String) HttpServletRequestUtil.getHttpServletRequest().getAttribute("uid");
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<SysUser>().eq(SysUser::getUid, uid);
        SysUser sysUser = getOne(lambdaQueryWrapper);
        BeanUtil.copyProperties(editUserInfoDTO, sysUser, false);
        boolean update = updateById(sysUser);
        if (update){
            return SystemResponse.success("修改成功");
        }
        return SystemResponse.fail("修改失败");
    }

    @Override
    public SysUser selectByOpenID(TeamFarDO teamFarDO) {
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.eq("wx_open_id", teamFarDO.getUid());
        return this.baseMapper.selectOne(sysUserQueryWrapper);
    }

    @Override
    public String selectOpenIDByUID(String uid) {
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.eq("uid", uid);
        return this.baseMapper.selectOne(sysUserQueryWrapper).getWxOpenId();
    }

}
